<?php

App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
App::import('Vendor', 'PHPExcel');
App::import('Vendor', 'IOFactory', array('file' => 'PHPExcel' . DS . 'IOFactory.php'));

/**
 * Subscribers Controller
 *
 * @property Subscriber $Subscriber
 */
class SubscribersController extends AppController {

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $this->Subscriber->recursive = 0;
        $this->set('subscribers', $this->paginate());
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        if (!$this->Subscriber->exists($id)) {
            throw new NotFoundException('Invalid subscriber', 'default', array('class' => 'alert alert-danger'));
        }
        $options = array('conditions' => array('Subscriber.' . $this->Subscriber->primaryKey => $id));
        $this->set('subscriber', $this->Subscriber->find('first', $options));
    }


    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if (!empty($this->request->data)) {
            if (!isset($this->Captcha)) { //if Component was not loaded throug $components array()
                $this->Captcha = $this->Components->load('Captcha'); //load it
            }
            $this->loadModel('Signup');
            $this->Signup->setCaptcha($this->Captcha->getVerCode()); //getting from component and passing to model to make proper validation check
            $this->Signup->set($this->request->data);
            if ($this->Signup->validates()) { //as usual data save call
                //$this->Signup->save($this->request->data);//save or something
                // validation passed, do something
                $this->Subscriber->create();
            	$this->request->data['Subscriber']['sub_date_added'] = date('Y-m-d H:i:s');
				if ($this->Subscriber->save($this->request->data)) {
					$this->Session->setFlash('Thank you for subscribing','default',array('class'=>'alert alert-info'));
					$this->redirect('/contents/view/home');
			}	else	{ //or
				$this->Session->setFlash('The subscriber could not be saved. Please, try again.','default',array('class'=>'alert alert-danger'));
				//pr($this->Signup->validationErrors);
				//something do something else
			}
		}
	}
}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
            
		if (!$this->Subscriber->exists($id)) {
			throw new NotFoundException('Invalid subscriber','default',array('class'=>'alert alert-danger'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			if ($this->Subscriber->save($this->request->data)) {
				$this->Session->setFlash('The subscriber has been successfully edited','default',array('class'=>'alert alert-info'));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('The subscriber could not be edited. Please, try again.','default',array('class'=>'alert alert-danger'));
			}
		} else {
			$options = array('conditions' => array('Subscriber.' . $this->Subscriber->primaryKey => $id));
			$this->request->data = $this->Subscriber->find('first', $options);
		}
	}

    /**
     * delete method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function email() { // C:\WAMP\BIN\PHP5.x.x.x\php.ini -> look for and comment out openssl.dll
        $this->set("subscribers", $this->Subscriber->find("all", array('order' => 'sub_date_added ASC')));
        $toList = array();
        $email = new CakeEmail('gmail');
        if ($this->request->is('post') || $this->request->is('put')) {
            $subList = array(); // array of newsletter recipients
            foreach ($this->data['Email']['checkbox'] as $id => $checked) {
                if ($checked) {
                    $sub = $this->Subscriber->query("select sub_id, sub_name, sub_email, sub_date_added, sub_active FROM subscribers where sub_id =" . $id);
                    $subList[] = array('sub_name' => $sub[0]['subscribers']['sub_name'], 'sub_email' => $sub[0]['subscribers']['sub_email']);
                }
            }

            $email->smtpOptions = array(
               'port'=>'465',
               'timeout'=>'30',
               'host' => 'ssl://smtp.gmail.com',
               'username'=>'amit.naik92@gmail.com',
               'password'=>'nikitanaik'
                 );
            
            foreach ($subList as $recipient) {
                $this->set('rec_name', $recipient['sub_name']);
                $email->addTo($recipient['sub_email']);
                if (empty($this->data['newsletters']['submittedfile']['tmp_name'])) {                    
                //do nothing
                } else {
                  // renames attachment to file that was sent.
                    $email->attachments(array($this->data['newsletters']['submittedfile']['name'] => $this->data['newsletters']['submittedfile']['tmp_name']));
                }
                $email->from('amit.naik92@gmail.com');
                $email->subject($this->data['newsletters']['subject']);
                $email->template = 'email_template'; // .ctp file in subscriber view folder
                $email->sendAs = 'Html';
                $emailMsg = 'Hello ' . $recipient['sub_name'] . '!' . "\n" . $this->data['newsletters']['message'];
                $email->send($emailMsg);
                
            

            }

            $this->Session->setFlash('All emails have been sent', 'default', array('class' => 'alert alert-info'));
        } else {
            
        }
    }

    /*   public function email()
      {
      $this->set("subscribers", $this->Subscriber->find("all", array('order' => 'sub_date_added ASC')));
      $toList = array();
      $email = new CakeEmail('gmail');
      if ($this->request->is('post') || $this->request->is('put'))
      {
      $list=0;
      foreach($this->data['Email']['checkbox'] as $id=>$checked)
      {
      if ($checked)
      {
      $list++;

      $sub = $this->Subscriber->query("select sub_id, sub_name, sub_email, sub_date_added, sub_active FROM subscribers where sub_id =".$id);
      $email->addTo($sub[0]['subscribers']['sub_email']);
      }
      }
      $email->attachments($this->data['newsletters']['submittedfile']['tmp_name']);
      $email->from('amit.naik92@gmail.com');
      $email->subject($this->data['newsletters']['subject']);
      $email->template = 'email_template'; // no .ctp :)
      $email->sendAs = 'html';
      $email->send($this->data['newsletters']['message']);
      $this->Session->setFlash(__('Email has been sent'));
      }
      else
      {

      }
      }
     */

    public function unsubscribe_delete($sub_email = null) {
        $this->Subscriber->sub_email = $sub_email;
        if (!$this->Subscriber->exists()) {
            throw new NotFoundException('Invalid subscriber', 'default', array('class' => 'alert alert-danger'));
        }
        $this->request->onlyAllow('post', 'unsubscribe_delete');
        if ($this->Subscriber->unsubscribe()) {
            $this->Session->setFlash('Subscriber deleted', 'default', array('class' => 'alert alert-info'));
            $this->redirect(array('controller' => 'Pages', 'action' => 'index'));
        }
        $this->Session->setFlash('Subscriber was not deleted', 'default', array('class' => 'alert alert-danger'));
    }

    public function unsubscribe() {
        if (!empty($this->data)) {
            $targetsub = $this->Subscriber->find('first', array(
                'conditions' => array('Subscriber.sub_email' => $this->data['Subscriber']['unsub_email'])));
            if (!empty($targetsub)) {
                $this->Subscriber->id = $targetsub['Subscriber']['sub_id'];
            }
            if (!$this->Subscriber->exists()) {
                //throw new NotFoundException(__('Invalid subscriber'));
                $this->Session->setFlash('Invalid subscriber', 'default', array('class' => 'alert alert-danger'));
            }
            //$this->request->onlyAllow('post', 'delete');
            if ($this->Subscriber->delete()) {
                $this->Session->setFlash('You Have Successfully Unsubscribed', 'default', array('class' => 'alert alert-info'));
                $this->redirect(array('controller' => 'pages', 'action' => 'home4'));
            }
            $this->Session->setFlash('Subscriber does not exist in database', 'default', array('class' => 'alert alert-danger'));
        }
    }

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('add', 'unsubscribe', 'captcha');
    }

    public function delete($id = null) {
        $this->Subscriber->id = $id;
        if (!$this->Subscriber->exists()) {
            throw new NotFoundException('Invalid subscriber', 'default', array('class' => 'alert alert-danger'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Subscriber->delete()) {
            $this->Session->setFlash('Subscriber deleted', 'default', array('class' => 'alert alert-info'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash('Subscriber was not deleted', 'default', array('class' => 'alert alert-danger'));
        $this->redirect(array('action' => 'index'));
    }

    public function captcha() {
        $this->autoRender = false;
        $this->layout = 'ajax';
        if (!isset($this->Captcha)) { //if Component was not loaded throug $components array()
            $this->Captcha = $this->Components->load('Captcha', array(
                'width' => 150,
                'height' => 50,
                'theme' => 'random',
            )); //load it
        }
        $this->Captcha->create();
    }

    public function excel() {
        // Find customer's details
        $myCustomer = $this->Subscriber->find('all');
        // Full name
        //$this->set('fullName', $myCustomer['Customer']['first_name'].' '.$myCustomer['Customer']['last_name']);
        //$fullName = $myCustomer['Subscriber']['sub_name'];
        // Full address
        //$this->set('fullAddress', $myCustomer['Customer']['street'].' '.$myCustomer['Customer']['suburb'].' '.$myCustomer['Customer']['postcode']);
        //$organisation = $myCustomer['Subscriber']['sub_organisation'];
        //$email = $myCustomer['Subscriber']['sub_email'];
        $inputFileType = 'Excel2007';
        $inputFileName = 'Subscribers.xlsx';
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
        $objPHPExcel->setActiveSheetIndex(0);
        $i = 1;
        foreach ($myCustomer as $customer):
            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $i, $customer['Subscriber']['sub_name']); // Fill in subscriber name
            $objPHPExcel->getActiveSheet()->SetCellValue('B' . $i, $customer['Subscriber']['sub_organisation']); // Fill in subscriber organisation
            $objPHPExcel->getActiveSheet()->SetCellValue('C' . $i, $customer['Subscriber']['sub_email']); // Fill in subscriber email
            $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
            $i++;
        endforeach;
        $objWriter->save('Subscribers.xlsx');
        $this->redirect('/app/webroot/Subscribers.xlsx');
    }

    public function excelRead() {
        //$this->Form->value('Quote.id');
        $fileName = $this->request->data['Subscriber']['filename'];
        //echo ('Your $fileName 1 is: '.$fileName.'<br>');
        $inputFileType = 'Excel2007';
        $inputFileName = 'Subscribers.xlsx' . $fileName; // Path to uploaded excel file
        //echo ('Your $inputFileName is: '.$inputFileName.'<br>');
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
        $objPHPExcel->setActiveSheetIndex(0);
        $quoteNumber = $objPHPExcel->getActiveSheet()->getCell('G2'); // Grab quote number
        $excelDate = $objPHPExcel->getActiveSheet()->getCell('I2')->getValue(); // Grab quote date
        $salesPrice = $objPHPExcel->getActiveSheet()->getCell('I43')->getValue(); //get quote price
        //convert date format to 'd/m/Y'
        $phpDate = PHPExcel_Shared_Date::ExcelToPHP($excelDate);
        $quoteDate = date('d-m-Y', $phpDate);

        //echo ('Your Subscriber number is: '.$SubscriberNumber.'<br>');
        //echo ('Subscriber date is: '.$excelDate.'<br>');
        //echo ('Subscriber date is: '.$phpDate.'<br>');
        //echo ('Subscriber date is: '.$SubscriberDate.'<br>');
        //$this->Subscriber->create();
        $this->request->data['Subscriber']['sub_name'] = $fullName;
        $this->request->data['Subscriber']['sub_organisation'] = $organisation;
        $this->request->data['Subscriber']['sub_email'] = $email;



        /* Ended */
    }

}
